<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="root"></div>
  <script>
    var historyObj = window.history;
    var root = document.getElementById("root");
    function updateContent (content){
      root.innerHTML = content;
    }
    window.addEventListener('popstate', () => {
      console.log('监听');
      updateContent(window.location.pathname)
    });
    // 调用pushState时并不会触发popstate事件，所以调用pushState的时候虽然路径变了，但内容并没有改变
    // opp 面向切片编程

    (function(historyObj){
      console.log('-----------------', historyObj);
      let oldPushState = historyObj.pushState;
      historyObj.pushState = function(state, title, url){
        let result = oldPushState.apply(historyObj, arguments);
        console.log('url', url);
        updateContent(url);
        return result;
      };
    })(history);

    setTimeout(() => {
      historyObj.pushState({page: 1}, '', '/page1');
    }, 1000)
    setTimeout(() => {
      historyObj.pushState({page: 2}, '', '/page2');
    }, 2000)
    setTimeout(() => {
      historyObj.pushState({page: 3}, '', '/page3');
    }, 3000)

    setTimeout(() => {
      historyObj.back()
    }, 4000)

  </script>
</body>
</html>